package com.sfy.login.third;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @Description
 * @Author 谷晓天
 * @Date 2021/7/5 11:33 上午
 */
public class JwtUtil {
    //生成
    public static String createJwt(String msg) {
        //指定签名算法
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
        //建造者对象
        JwtBuilder builder = Jwts.builder()
                .signWith(algorithm,createKey())//设置签名密钥
                .setId(UUID.randomUUID().toString())//设置唯一标记，防止重放攻击
                .setIssuedAt(new Date())//设置生成时间
                .setSubject(msg);//设置存放内容
        //生成令牌
        return builder.compact();
    }

    //解析
    public static String parseJwt(String jwt) {
        return Jwts.parser().setSigningKey(createKey())
                .parseClaimsJws(jwt).getBody().getSubject();
    }

    //生成密钥
    private static Key createKey() {
        String key = "love_cook";
        return new SecretKeySpec(Base64.getEncoder().encode(key.getBytes()),"AES");
    }
}
